from flask import render_template, current_app, g, jsonify, abort, request
from info import constants, db
from info.models import News, Comment, CommentLike, User
from info.modules.news import news_blu
from info.utils.common import user_login_data
from info.utils.response_code import RET


@news_blu.route('/followed_user', methods=["POST"])
@user_login_data
def followed_user():
    """
    关注用户逻辑的实现
    1.接收参数，作者id、关注/取消关注动作
    2.校验参数
    3.取到被关注的用户
    4.根据action执行相关操作
    5.返回响应
    :return:
    """
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="未登录")
    user_id = request.json.get("user_id")
    action = request.json.get("action")
    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    if action not in ["follow", "unfollow"]:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 取到要被关注的用户
    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')
    if not other:
        return jsonify(errno=RET.DATAERR, errmsg='未查询到该作者')
    # 根据action执行相关操作
    if action == "follow":
        if other not in user.followed:
            user.followed.append(other)
        else:
            return jsonify(errno=RET.DATAEXIST, errmsg="当前用户已被关注")
    else:
        if other in user.followed:
            user.followed.remove(other)
        else:
            return jsonify(errno=RET.NODATA, errmsg="当前用户未被关注")
    return jsonify(errno=RET.OK, errmsg='OK')


@news_blu.route('/comment_like', methods=['post'])
@user_login_data
def comment_like():
    """
    评论点赞功能逻辑
    1.接受参数，新闻id、评论id、点赞/取消点赞动作action
    2.校验参数
    3.获取到要被点赞的评论
    4.判断是点赞还是取消
    :return:
    """
    user = g.user
    if not user:
        return jsonify(errno=RET.LOGINERR, errmsg='用户未登录')
    comment_id = request.json.get("comment_id")
    action = request.json.get("action")
    if not all([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    if action not in ["add", "remove"]:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        comment_id = int(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')
    if not comment:
        return jsonify(errno=RET.DATAERR, errmsg='评论不存在')
    # 执行点赞动作
    if action == "add":
        comment_like_model = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                      CommentLike.user_id == user.id).first()
        # 该条新闻未被点赞时
        if not comment_like_model:
            comment_like_model = CommentLike()
            comment_like_model.comment_id = comment_id
            comment_like_model.user_id = user.id
            db.session.add(comment_like_model)
            # 该评论的点赞数量加一
            comment.like_count += 1
    # 取消点赞
    else:
        comment_like_model = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                      CommentLike.user_id == user.id).first()
        if comment_like_model:
            db.session.delete(comment_like_model)
            comment.like_count -= 1
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")
    return jsonify(errno=RET.OK, errmsg='OK')


@news_blu.route('/news_comment', methods=['post'])
@user_login_data
def news_comment():
    """
    新闻评论逻辑
    1.接收参数，新闻id、评论内容comment、父评论id
    2.校验参数
    3.查询新闻是否存在
    4.初始化一个评论模型，添加到mysql
    5.将数据返回给前端显示界面
    :return:
    """
    user = g.user
    if not user:
        return jsonify(errno=RET.LOGINERR, errmsg='用户未登录')
    news_id = request.json.get('news_id')
    comment_content = request.json.get('comment')
    parent_id = request.json.get('parent_id')
    if not all([news_id, comment_content]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')
    if not news:
        return jsonify(errno=RET.NODATA, errmsg='未查询新闻数据')
    comment = Comment()
    comment.content = comment_content
    comment.news_id = news_id
    comment.user_id = user.id
    if parent_id:
        comment.parent_id = parent_id
    # 添加到数据库
    # 为什么要自己去commit()?，因为在return的时候需要用到 comment 的 id
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
    return jsonify(errno=RET.OK, errmsg='OK', data=comment.to_dict())


@news_blu.route('/news_collect', methods=['post'])
@user_login_data
def news_collect():
    """
    1.接受参数，新闻id、收藏动作action
    2.校验参数
    3.查询新闻是否存在
    4.判断执行收藏&取消收藏动作
    5.返回响应
    :return:
    """
    # 判断用户是否登录
    user = g.user
    if not user:
        return jsonify(errno=RET.LOGINERR, errmsg='用户未登录')
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    if action not in ["collect", "cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')
    if not news:
        return jsonify(errno=RET.NODATA, errmsg='未查询新闻数据')
    if action == 'cancel_collect':
        if news in user.collection_news:
            user.collection_news.remove(news)
    else:
        if news not in user.collection_news:
            user.collection_news.append(news)
    return jsonify(errno=RET.OK, errmsg='操作成功')


@news_blu.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
    """
    新闻详情页面展示
    :param news_id:从前端传入的新闻id参数
    :return:
    """
    user = g.user
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())
    if not news_id:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
    if not news:
        abort(404)
    news.clicks += 1
    # 新闻默认未收藏，判断用户是否收藏
    is_collected = False
    if user:
        if news in user.collection_news:
            is_collected = True
    # 展示当前新闻评论内容
    comments = []
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
    comment_like_ids = []
    if user:
        # 如果用户已登录，需要显示当前新闻里哪些是该用户点赞过的评论
        try:
            # 查询出当前新闻的所有评论列表，并取到所有评论id
            comment_ids = [comment.id for comment in comments]
            # 查询当前哪些评论被该用户点过赞
            comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids),
                                                     CommentLike.user_id == user.id).all()
            # 取到所有被点赞评论的id
            comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]
        except Exception as e:
            current_app.logger.error(e)
    comment_dict_li = []
    for item in comments:
        comment_dict = item.to_dict()
        # 评论默认未点赞
        comment_dict["is_like"] = False
        # 如果评论在被点赞列表里
        if item.id in comment_like_ids:
            comment_dict["is_like"] = True
        comment_dict_li.append(comment_dict)
    # 当前新闻作者默认未关注，判断用户是否关注
    is_followed = False
    # 如果当前新闻有作者
    if news.user and user:
        # 如果当前作者被用户关注
        if news.user in user.followed:
            is_followed = True

    data = {
        "user": user.to_dict() if user else None,
        "news_dict_li": news_dict_li,
        "news": news.to_dict(),
        "is_collected": is_collected,
        "is_followed": is_followed,
        "comments": comment_dict_li,
    }
    return render_template('news/detail.html', data=data)
